package com.dq.demos.web.utils;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.sm.misc.BASE64Encoder;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.protocol.HttpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.Exception;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class BIPUtil {

    /**
     * 接口请求
     * @param url
     * @param queryParams
     * @param bodyParm
     * @return
     */
    public static String getPostQueryParamAndBodyParam(String url, Map queryParams, Object bodyParm) {
        String httpResponse = HttpClientUtil.doPost(url, null, queryParams, bodyParm);
        return httpResponse;
    }
    /**
     * 获取token
     * @param apiUrl
     * @param appKey
     * @param appSecret
     * @return
     */
    public static String getAccessToken(String apiUrl, String appKey, String appSecret) {
        String access_token = null;
        Map<String, Object> params = new HashMap<>();
        // 除签名外的其他参数
        params.put("appKey", appKey);
        params.put("timestamp", System.currentTimeMillis());
        // 计算签名
        try {
            String signature = sign(params, appSecret);
            params.put("signature", signature);
            // 请求
//            String httpResponse = HttpClientUtil.doGet(apiUrl, null, params);
            String httpResponse = HttpReqThirdPartyUtils.sendGet(apiUrl, null, params, "oalog");
            if (StringUtils.isNotBlank(httpResponse)) {
                access_token = JSONObject.parseObject(httpResponse).getJSONObject("data").getString("access_token");
//                access_token = JSONUtil.parseObj(JSONUtil.parseObj(httpResponse).get("data")).get("access_token").toString();
            }
        } catch (Exception e) {
        }
        return access_token;
    }
    /**
     * 接口数据加密
     *
     * @param params
     * @param suiteSecret
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     * @throws UnsupportedEncodingException
     */
    public static String sign(Map<String, Object> params, String suiteSecret) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
        Map<String, Object> treeMap;
        if (params instanceof TreeMap) {
            treeMap = params;
        } else {
            treeMap = new TreeMap<>(params);
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (Map.Entry<String, Object> entry : treeMap.entrySet()) {
            stringBuilder.append(entry.getKey()).append(entry.getValue());
        }
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(suiteSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringBuilder.toString().getBytes(StandardCharsets.UTF_8));
        BASE64Encoder encode = new BASE64Encoder();
        String base64String = encode.encode(signData);
         return URLEncoder.encode(base64String, "UTF-8");
    }
}
